//https://github.com/mzabriskie/axios
import axios from 'axios';
import qs from './querystring2';
import { userCenterGetTokenInfo, userCenterErrorHandler } from './userCenter';
import { randomString, useTimezone } from 'pub-bbx-utils'
import i18n from '@src/locales'
import { httpHeaderKey } from 'pub-bbx-global/lang/dist'

let alertLoginAgain = false

axios.interceptors.request.use(config => {
  const tokenInfo = userCenterGetTokenInfo()
  if (tokenInfo.token && tokenInfo.shbVersion) {
    config.headers['token'] = tokenInfo.token
    config.headers['shbVersion'] = tokenInfo.shbVersion
  }
  config.headers['timeZone'] = useTimezone().timezone
  config.headers[httpHeaderKey] = i18n.locale; // 传递语言环境
  return config;
}, error => {
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
  if(alertLoginAgain) return
  if(response.data.status == '2016' || response.data.status == '2021') alertLoginAgain = true
  
  // 用户中心错误处理
  userCenterErrorHandler(response);
  return response;
}, error => {
  return Promise.reject(error); // 返回一个空对象，主要是防止控制台报错
});

function addPrefix(url){
  if(location.port !== '') {
    url = '/serve' + url
  }
  return url.replace(/\/\//g, '/')
}

function http(method = 'get', url = '', config = {}){
  config.url = addPrefix(url);
  config.method = method;

  return axios.request(config).then(response => response.data);
}

function get(url = '', data = {}, config = {}){
  if(null != data){
    let params = qs.stringify(data);
    let hyphen = url.indexOf('?') != -1 ? "&" : "?";
    let randomStr = params ? `&_t=${randomString()}` : `_t=${randomString()}`;
    url = url + hyphen + params + randomStr
  }

  return http('get', url, config);
}

function post(url = '', data = {}, emulateJSON = true, config = {}){
  data = emulateJSON ? data : qs.stringify(data);
  config.data = data;

  return http('post', url, config);
}

function ajax(url) {
  return new Promise(function(resolve,reject){
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      var response = this.responseText;
      try {
        response = JSON.parse(response)
      } catch (e){
        console.error(e)
      }
      resolve(response)
    };
    
    xhr.onerror = err => reject(err);
    xhr.open("get", url, true);
    xhr.send();
  })
}


export default {
  get,
  post,
  ajax
};
